<?php

namespace App\Http\Middleware;

use Closure;

class CheckAdminLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //检查用户是否登录
        if(!auth()->check()){
            return redirect(route('admin.login'))->with('error','请先登录');
        }
        //得到当前请求的路由别名
        $routename=$request->route()->getName();
        //得到当前登陆用户模型
        $userModel=auth()->user();
        //得到当前用户对应的角色模型
        $roleModel=$userModel->role;
        //定义不用进行权限验证的路由
        $allow=[
            'admin.logout',
            'admin.index',
            'admin.welcome'
        ];
        //得到当前用户拥有的权限
        $nodeList=$roleModel->nodes()->where('pid','<>',0)->pluck('route_name')->toArray();
        $nodeList=array_merge($nodeList,$allow);
        //权限添加到$request属性中
        $request->nodeList=$nodeList;
        $request->username=$userModel->username;
        //超级管理员不受权限控制
        if($userModel->username!='admin'&&!in_array($routename,$nodeList)){
            die('没有权限');
        }
        //向下执行
        return $next($request);
    }
}
